#! /usr/bin/python

import sys
import os
import time
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('..')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        #entry = "Starting Organization Behaviour"
        #self.addBehaviour(Organization.AgentOrganization(self,nick="nick", name="sala", goalList=[],agentList=["agent@tatooine.dsic.upv.es"]))
        pass
    def _process(self):
        pass

class MyOrganization(Organization.Team):
    def _process(self):
        print self.getOwner()
        #self.setGoal("eoeoeoeo")
        print self.getGoal()
        list=self.getUnitList()
        d={"mision":"supervision"}
        for l in list:
            b=self.requestEntryUnit(l,d)
            if b:
                m=MyUnit(self.myAgent,nick="e",password="pass",name=l)
                self.joinUnit(m)



class MyUnit(Unit.Team):
    def _process(self):
        print "Unit"
        if self.requestLeadership():
            self.permanentExpulsion("example2@apolo.dsic.upv.es")
            try:
                 print self.getGoal()
                 print self.getMemberList()
                 print self.getNumberOfAgents()
                 m=ACLMessage.ACLMessage()
                 m.setPerformative("inform")
                 m.setSender(self.myAgent.getAID())
                 m.addReceiver(self.myAgent.getAID())
                 self.sendMessage(m)
                 print "Enviado"
            except:
                print "Excepcion"
        time.sleep(10)
        # self.setGoal("goal")
       # print self.getGoal()
       # print self.getMemberList()
       # print self.getNumberOfAgents()

        """
            d={"mision":"supervision"}
            b=self.requestCreationPermission(d)
            if b:
                m=MyUnit2(self.myAgent,nick="jefe",password="pass",name="escalera")
                self.addUnit(m)
                time.sleep(30)
                mens=self.receiveMessage()
                if mens:
                    if mens.getPerformative()=="request":
                        sum= m.askMembers()
                        print sum
                        m=ACLMessage.ACLMessage()
                        m.setPerformative("inform")
                        m.setSender(self.myAgent.getAID())
                        m.addReceiver(mens.getSender())
                        self.sendPrivateMessage(mens.getSender().getName(),m)

                else:
                    print "Sin mensaje"
            """


class MyUnit2(Unit.Hierarchy):
    def _process(self):
            time.sleep(10)

    def askMembers(self):
            sum=0
            m=ACLMessage.ACLMessage()
            m.setPerformative("request")
            m.setSender(self.myAgent.getAID())
            m.addReceiver(self.myAgent.getAID())
            m.setContent("Trabajo??")
            mem=self.getMemberList()
            print "dentro de ask"+str(mem)
            for i in mem:
               self.sendPrivateMessage(i,m)
            for i in mem:
               res=self.receiveMessage()
               if res:
                 print res.getContent()
                 sum=sum+res.getContent()
            return sum

    def entryUnitTest(self,sender,desc=None):
      d=desc
      if d.has_key("zona"):
           if str(d["zona"])=="escalera":
               return True
      return False

if __name__ == "__main__":
    """
    host = os.getenv("HOSTNAME")
    if host == None:
        host = split(os.getenv("SESSION_MANAGER"),"/")[1][:-1]
        if host == None:
    """

agent = "e@apolo.dsic.upv.es"
#agent = "agent2@thx1138.dsic.upv.es"


print "Agent "+agent+" registering"
b = Example(agent,"pasword")
b.start()
time.sleep(3)
lista= b.getOrganizationList()
print lista
for i in lista:
    o=MyOrganization(b,nick="e", name=i)
    b.joinOrganization(o)